package com.stedu.mall.orderservice.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.*;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.*;
import com.stedu.mall.orderservice.mapper.CartMapper;
import com.stedu.mall.orderservice.mapper.OrderDetailMapper;
import com.stedu.mall.orderservice.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddrService addrService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartMapper cartMapper;
    @DubboReference
    private UserService userService;
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void insert(OrderVo orderVo) throws SteduException {
        /*
        1、生成订单
        1)生成订单ID - 雪花算法生成
        2)获取地址对象 *
        3)设置地址详情
        4)添加订单
        2、生成详情
        1)获取购物车 - 判断购物车是否合法
        2) 获取商品信息
        是否存在
        是否下架
        库存是否充足
        3)减去商品库存
        4)添加详情
        3、删除购物车
        * */
        //创建订单对象
        Order order = new Order();
        //生成订单id
        String orderId = IdUtil.getSnowflakeNextIdStr();
        //设置订单id
        order.setId(orderId);
        //获取地址对象
        Addr addr = addrService.selectById(orderVo.getAddrId());
        //设置地址详情
        order.setAddrDetail(addr.getContact() + "-"
                + addr.getPhone() + "-"
                + addr.getProvince() + "-"
                + addr.getCity() + "-"
                + addr.getDistrict() + "-"
                + addr.getAddress() + "-"
                + addr.getStreet());
        //添加订单
        order.setUserId(orderVo.getUserId());
        order.setPayType(0);
        order.setAddrId(orderVo.getAddrId());
        order.setStatus(0);
        orderMapper.insert(order);
        //生成订单详情 每个购物车的id对应一个商品详情
        for (Integer cartId : orderVo.getCartIds()) {
            //获取购物车
            Cart cart = cartMapper.selectById(cartId);
            if (cart == null) {
                throw new SteduException("购物车不存在，无法生成订单");
            }
            if (!cart.getUserId().equals(orderVo.getUserId())) {
                throw new SteduException("购物车不属于当前用户，无法生成订单");
            }
            //获取商品信息
            Goods goods = goodsService.selectById(cart.getGoodsId());
            //是否存在
            if (goods == null) {
                throw new SteduException("商品不存在，无法生成订单");
            }
            //是否下架
            if (goods.getStatus().equals(0)) {
                throw new SteduException("商品已下架，无法生成订单");
            }
            //库存是否充足
            if (goods.getCount() < cart.getCount()) {
                throw new SteduException("商品库存不足，无法生成订单");
            }
            //减去商品库存
            goods.setCount(goods.getCount() - cart.getCount());
            goodsService.update(goods);
            //添加详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCount(cart.getCount());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setOrderId(orderId);
            orderDetail.setGoodsId(goods.getId());
            orderDetailMapper.insert(orderDetail);
        }
        //删除购物车
        cartMapper.deleteByIds(Arrays.asList(orderVo.getCartIds()));
        orderVo.setOrderId(orderId);
    }


    @Override
    public boolean update(Order order) throws SteduException {
        //判断商品是否存在
        if (orderMapper.selectById(order.getId()) == null) {
            throw new SteduException("该订单不存在，修改失败！");
        }
        return orderMapper.update(order)>=1;
    }

    @Override
    public boolean delete(String id) throws SteduException {
//        if (orderMapper.selectById(id) == null) {
//            throw new SteduException("该订单不存在，修改失败！");
//        }
        return orderMapper.delete(id)>=1;
    }

    @Override
    public Order selectById(String id,Integer userId) throws SteduException {
        //根据订单id进行查询
        Order order = orderMapper.selectById(id);
        //判断订单是否属于当前用户
        if(!order.getUserId().equals(userId)){
            throw new SteduException("该订单不属于当前用户，无法查询！");
        }
        //查询订单详情对应商品的信息
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            //使用dubbo调用goods_service查询商品信息
            Goods goods = goodsService.selectById(orderDetail.getGoodsId());
            orderDetail.setGoods(goods);

        }
        return order;
    }
    //不用第三方插件用Limit关键字进行分页查询
    @Override
    public PageInfo<Order> selectByCondition(Order condition, Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //查询
        List<Order> orderList = orderMapper.selectByCondition(condition);
        orderList.stream().forEach(order -> {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            orderDetails.stream().forEach(orderDetail -> {
                Goods goods = goodsService.selectById(orderDetail.getGoodsId());
                orderDetail.setGoods(goods);
            });
            order.setOrderDetails(orderDetails);
        });
        //创建分页信息
        PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
        return orderPageInfo;
    }
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void pay(OrderVo orderVo) throws SteduException {
        //查询订单
        Order order = orderMapper.selectById(orderVo.getOrderId());
        //判断订单是否存在
        if (order == null) {
            throw new SteduException("订单不存在，无法支付");
        }
        //判断订单是否属于当前用户
        if (!order.getUserId().equals(orderVo.getUserId())) {
            throw new SteduException("订单不属于当前用户，无法支付");
        }
        //查看当前订单是否是未支付状态
        if (!order.getStatus().equals(0)) {
            throw new SteduException("订单已支付，无法再次支付");
        }
        //更新订单状态为1 支付状态为0
        order.setStatus(1);
        order.setPayType(0);
        //更新订单
        orderMapper.update(order);
        //根据用户id查询用户
        User user = userService.selectById(order.getUserId());
        //判断支付密码是否存在、正确
        String payPassword = user.getPayPassword();
        if (payPassword == null) {
            throw new SteduException("支付密码未设置，无法支付");
        }
        String md5 = SecureUtil.md5(SecureUtil.md5(orderVo.getPayPassword() + user.getSalt()));
        if (!payPassword.equals(md5)) {
            throw new SteduException("支付密码错误，请重试");
        }
        //计算当前订单总金额
        BigDecimal sum = new BigDecimal("0");
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            sum = sum.add(orderDetail.getPrice().multiply(new BigDecimal(orderDetail.getCount())));
        }
        //判断金额是否充足
        if (user.getMoney().compareTo(sum) < 0) {
            throw new SteduException("余额不足，无法支付");
        }
        //扣除余额
        User u = new User();
        u.setId(user.getId());
        u.setMoney(user.getMoney().subtract(sum));
        userService.pay(u);
    }

    @Override
    public List<Map<String, Integer>> selectProCount() {
        List<Map<String, Integer>> maps = orderMapper.selectProCount();
        return maps;
    }
    //收发货
    @Override
    public String updategood(Order order) {

        if (order.getStatus() !=null && order.getStatus()== 2){
            order.setStatus(3);
            orderMapper.update(order);
            return "已收货";
        }else {
            //设置发货状态
            order.setStatus(2);
            orderMapper.update(order);
            return "已发货";
        }


    }
}
